<script setup>
import ProTable from '@/components/ProTable/index.vue'
import Details from '@/components/ProTable/Details.vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { getDepts } from '@/api/system/dept'
import WarningTextBtn from '@/components/ProTable/WarningTextBtn.vue'
import {
  queryInspectProject,
  querySubListByProjId,
  queryRoleRelevanceUsers,
  downloadPost,
  inspectPlanTurnover,
  queryProjInspectCompany,
  checkInspectCompanyEdit,
  inspectPlanResultScoreExport,
  getDownloadName,
  del,
  getTable,
  add,
  edit
} from '@/api/modelQuality/inspectPlan'
import { Message } from 'element-ui'
import { useGetEnum } from './public'

const { dictEnumReveal, getEnumlabel, optionFunc } = useGetEnum()

// 获取 主承接 下拉框的枚举字段
const mainUndertaking = ref()
const getMainUndertaking = async() => {
  const params = { enabled: true, isExternal: false }
  const _res = await getDepts(params)
  const pid = _res.content[0].id
  const res = await getDepts({ ...params, pid })
  const arr = res.content.filter((item) => item.label !== '股份总部')
  mainUndertaking.value = arr
}
// 获取 观察员 下拉框的枚举字段
const observer = ref()
const getObserver = () => {
  queryRoleRelevanceUsers({ roleName: '观察员' }).then((res) => {
    observer.value = res
  })
}
// 下拉框的数据
const options = reactive({
  project: [], // 工程号/主合同号/项目编号
  subitem: [], // 子项号
  observer: [], // 观察员
  presidingUnit: [] //  主持单位
})
const proTableRef = ref()
// 表格配置项
const tableColumn = ref([
  {
    type: 'selection',
    dataIndex: 'selection'
  },
  {
    title: '评审场次',
    dataIndex: 'reviewMonth',
    option: 'inspect_plan_review_month'
  },
  {
    title: '主承接',
    dataIndex: 'deptName'
  },
  {
    title: '工程号/主合同号/项目编号',
    width: 240,
    dataIndex: '--',
    render: (e) => `
    ${e.constructionCode || '空'} /
    ${e.contractCode || '空'} /
    ${e.projCode || '空'}`
  },
  {
    title: '项目名称',
    dataIndex: 'projName'
  },
  {
    title: '子项号/子项名称',
    width: 160,
    dataIndex: 'subId',
    render: (e) => `${e.subId} / ${e.subName}`
  },
  {
    title: '申报节点',
    dataIndex: 'declareNode',
    option: 'inspect_plan_declare_node'
  },
  {
    title: '审查方',
    width: 160,
    dataIndex: '---',
    render: (e) => `${e.inspect1CompanyName} / ${e.inspect2CompanyName}`
  },
  {
    title: '观察员',
    dataIndex: 'observerName'
  },
  {
    title: '会议日期',
    dataIndex: 'meetingDate',
    width: 100
  },
  {
    title: '会议时间',
    width: 160,
    dataIndex: 'meetingTime'
  },
  {
    title: '更新者',
    dataIndex: 'updateBy'
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 160
  },
  {
    title: '审查状态',
    dataIndex: '_shenchaStatus',
    slot: 'table_column_status',
    fixed: 'right'
  },
  {
    title: '操作',
    width: 300,
    dataIndex: 'operate',
    slot: 'table_operate',
    fixed: 'right'
  }
])
// 搜索配置项
const searchColumn = ref([
  {
    type: 'input',
    width: 300,
    dataIndex: 'searchColumn',
    label: '工程号、主合同号、项目编号及项目名称'
  },
  {
    type: 'select',
    dataIndex: 'reviewMonth',
    label: '评审场次',
    option: 'inspect_plan_review_month'
  },
  {
    type: 'select',
    dataIndex: 'deptId',
    label: '主承接',
    optionValue: 'id',
    option: mainUndertaking
  },
  {
    type: 'select',
    dataIndex: 'declareNode',
    label: '申报节点',
    option: 'inspect_plan_declare_node'
  },
  {
    type: 'select',
    dataIndex: 'observerId',
    label: '观察员',
    option: observer,
    optionLabel: 'nickName',
    optionValue: 'userId'
  },
  {
    type: 'select',
    dataIndex: 'inspectStatus',
    label: '审查状态',
    option: 'inspect_plan_status'
  }
])
// 新增&编辑配置项
const formColumn = ref([
  {
    type: 'divider',
    label: '基本信息'
  },
  {
    type: 'select',
    dataIndex: 'reviewMonth',
    label: '评审场次',
    option: 'inspect_plan_review_month',
    disabled: computed(() => isEditFrom.value)
  },
  {
    type: 'select',
    dataIndex: 'projId',
    label: '工程号/主合同号/项目编号',
    placeholder: '请输入关键词',
    option: computed(() => options.project),
    disabled: computed(() => inspectStatus.value !== '0' && isEditFrom.value),
    optionLabel: 'joinStr',
    optionValue: 'projId',
    filterable: true,
    change: (e) => projIdChange(e)
  },
  {
    type: 'text',
    dataIndex: 'deptName',
    label: '主承接',
    value: computed(() => currentSelectProjct?.value?.deptName || '--')
  },
  {
    type: 'text',
    dataIndex: 'projName',
    label: '项目名称',
    disabled: computed(() => inspectStatus.value !== '0' && isEditFrom.value),

    value: computed(() => currentSelectProjct?.value?.projName || '--')
  },
  {
    type: 'select',
    dataIndex: 'subId',
    label: '子项号',
    option: computed(() => options.subitem),
    optionLabel: 'subNo',
    optionValue: 'subId',
    change: (e) => subIdChange(e)
  },
  {
    type: 'text',
    dataIndex: 'subName',
    label: '子项名称',
    value: computed(() => stateText.subName || '--')
  },
  {
    type: 'select',
    dataIndex: 'declareNode',
    label: '申报节点',
    option: 'inspect_plan_declare_node',
    disabled: computed(() => inspectStatus.value !== '0' && isEditFrom.value)
  },
  {
    type: 'multiple',
    dataIndex: 'designSoftware_',
    label: '设计软件',
    option: 'software',
    disabled: computed(() => inspectStatus.value !== '0' && isEditFrom.value),

    parameProcess: [
      'designSoftware',
      (arr) => arr.join(','),
      (str) => str.split(',')
    ]
  },
  {
    type: 'textarea',
    dataIndex: 'remark',
    label: '补充信息',
    maxlength: 255
  },
  {
    type: 'divider',
    label: '参与方信息'
  },
  {
    type: 'text',
    dataIndex: 'deptName_',
    label: '被检查方公司',
    value: computed(() => currentSelectProjct?.value?.deptName || '--')
  },
  {
    type: 'text',
    dataIndex: 'inspectionParty',
    label: '被检查方账户',
    value: computed(() => stateText?.inspectionParty || '--')
  },
  {
    type: 'select',
    dataIndex: 'inspect1CompanyId',
    label: '检查方1公司',
    option: mainUndertaking,
    optionValue: 'id',
    disabled: computed(() =>
      isEditFrom.value
        ? disabledInspect.value
          ? disabledInspect.value
          : inspectStatus.value !== '0'
        : disabledInspect.value
    ),
    optionSlot: 'inspect1CompanyId_optionSlot',
    change: (e) => inspectChange(e, 1)
  },
  {
    type: 'text',
    dataIndex: 'inspectionParty_1',
    label: '检查方1账户',
    value: computed(() => stateText?.inspectionParty_1 || '--')
  },
  {
    type: 'select',
    dataIndex: 'inspect2CompanyId',
    label: '检查方2公司',
    optionValue: 'id',
    option: mainUndertaking,
    disabled: computed(() =>
      isEditFrom.value
        ? disabledInspect.value
          ? disabledInspect.value
          : inspectStatus.value !== '0'
        : disabledInspect.value
    ),
    optionSlot: 'inspect2CompanyId_optionSlot',
    change: (e) => inspectChange(e, 2)
  },
  {
    type: 'text',
    dataIndex: 'inspectionParty_2',
    label: '检查方2账户',
    value: computed(() => stateText?.inspectionParty_2 || '--')
  },
  {
    type: 'select',
    dataIndex: 'observerId',
    label: '观察员',
    option: observer,
    optionLabel: 'nickName',
    optionValue: 'userId',
    disabled: computed(() => inspectStatus.value !== '0' && isEditFrom.value)
  },
  {
    type: 'divider',
    label: '会议信息'
  },
  {
    type: 'date',
    dataIndex: 'meetingDate',
    label: '会议日期'
  },
  {
    type: 'select',
    dataIndex: 'meetingTime',
    label: '会议时间',
    option: 'inspect_plan_meeting_time',
    optionValue: 'label'
  },
  {
    type: 'select',
    dataIndex: 'presideCompanyId',
    label: '主持单位',
    optionValue: 'id',
    option: computed(() => options.presidingUnit),
    disabled: computed(() => inspectStatus.value !== '0' && isEditFrom.value)
  },
  {
    type: 'input',
    dataIndex: 'meetingNo',
    label: '会议号',
    maxlength: 20
  },
  {
    type: 'input',
    dataIndex: 'meetingPassword',
    label: '会议密码',
    maxlength: 20
  },
  {
    type: 'textarea',
    dataIndex: 'meetingRemark',
    label: '其他信息',
    maxlength: 255
  }
])
// 默认表单数据
const defaultForm = {
  reviewMonth: null,
  projId: null,
  subId: null,
  declareNode: null,
  designSoftware: null,
  designSoftware_: null,
  remark: null,
  inspect1CompanyId: null,
  inspect2CompanyId: null,
  observerId: null,
  meetingDate: null,
  meetingTime: null,
  presideCompanyId: null,
  meetingNo: null,
  meetingPassword: null,
  meetingRemark: null
}
// 表单效验
const formRules = {
  reviewMonth: [
    { required: true, message: '评审场次不能为空', trigger: 'blur' }
  ],
  projId: [
    {
      required: true,
      message: '工程号/主合同号/项目编号不能为空',
      trigger: 'blur'
    }
  ],
  subId: [{ required: true, message: '子项号不能为空', trigger: 'blur' }],
  inspect1CompanyId: [
    { required: true, message: '检查方1公司不能为空', trigger: 'blur' }
  ],
  inspect2CompanyId: [
    { required: true, message: '检查方2公司不能为空', trigger: 'blur' }
  ],
  declareNode: [
    { required: true, message: '申报节点不能为空', trigger: 'blur' }
  ]
}
// 权限
const permission = {
  add: ['admin', 'inspectPlan:add'],
  edit: ['admin', 'inspectPlan:edit'],
  del: ['admin', 'inspectPlan:del'],
  turnover: ['admin', 'inspectPlan:turnover'],
  download: ['admin', 'inspectPlan:download'],
  scoreResult: ['admin', 'inspectPlan:scoreResult']
}

const disabledInspect = ref(false)

// 表单中 目前选中的项目
const currentSelectProjct = ref({})
// 表单中 静态显示的信息
const stateText = reactive({
  subName: '', // 子项名称
  inspectionParty: '', // 被检查方公司
  inspectionParty_1: '', // 检查方1账户
  inspectionParty_2: '' // 检查方2账户
})
const projIdChange = (projId, isEdit) => {
  currentSelectProjct.value = options.project.find(
    (item) => item.projId === projId
  )
  // 查询项目的审查公司信息
  if (!isEdit) {
    queryProjInspectCompany({ projId }).then((res) => {
      if (Object.keys(res).length) {
        disabledInspect.value = true
        DetailsRef.value.submitForm['inspect1CompanyId'] =
          res.inspect1CompanyId
        DetailsRef.value.submitForm['inspect2CompanyId'] =
          res.inspect2CompanyId
        inspectChange(res.inspect1CompanyId, 1)
        inspectChange(res.inspect2CompanyId, 2)
      } else {
        disabledInspect.value = false
      }
    })
  }

  // 查询评分员信息并更新状态文本
  queryRoleRelevanceUsers({
    roleName: '评分员',
    deptName: currentSelectProjct.value.deptName
  }).then((res) => {
    if (res.length > 0) {
      stateText.inspectionParty = res?.map((item) => item.username)?.join('、')
    } else {
      stateText.inspectionParty = ''
    }
  })

  // 查询项目子项列表并更新选项列表
  return querySubListByProjId({ projId }).then((res) => {
    options.subitem = res
    if (isEdit) return // 避免详情进入清除数据
    DetailsRef.value.submitForm['subId'] = null
    stateText.subName = ''
  })
}

const subIdChange = (subId) => {
  // 更新当前子项名称文本
  stateText.subName = options.subitem.find(
    (item) => item.subId === subId
  )?.subName
}

const inspectChange = (id, index, isEdit) => {
  // 更新第一个审查公司的相关信息
  options.presidingUnit[index - 1] = mainUndertaking.value.find(
    (item) => item.id === id
  )
  queryRoleRelevanceUsers({
    roleName: '评分员',
    deptName: options.presidingUnit[index - 1]?.name
  }).then((res) => {
    if (res.length > 0) {
      stateText['inspectionParty_' + index] = res
        ?.map((item) => item.username)
        ?.join('、')
    } else {
      stateText['inspectionParty_' + index] = ''
    }
  })
  if (isEdit) return // 避免详情进入清除数据
  DetailsRef.value.submitForm['presideCompanyId'] = null
}

// 弹窗关闭，非常规数据置空
const detailsClose = (isRefresh) => {
  isEditFrom.value = false
  disabledInspect.value = false
  inspectStatus.value = null
  Object.keys(stateText).forEach((key) => {
    stateText[key] = ''
  })
  currentSelectProjct.value = {}
  if (isRefresh) {
    proTableRef.value.getTableData()
  }
}

const DetailsRef = ref(null)

const leftOptionChange = (e) => {
  switch (e) {
    case 'export':
      onDownload()
      break
    case 'add':
      DetailsRef.value.beforeOpen(e)
      break

    default:
      console.log('点击事件未定义')
      break
  }
}

const isEditFrom = ref(false)
const inspectStatus = ref(null)
const onEdit = async(row) => {
  isEditFrom.value = true
  inspectStatus.value = row.inspectStatus
  DetailsRef.value.beforeOpen('edit', row)

  await remoteMethod()
  await projIdChange(row.projId, true)
  subIdChange(row.subId)
  inspectChange(row.inspect1CompanyId, 1, true)
  inspectChange(row.inspect2CompanyId, 2, true)

  checkInspectCompanyEdit({ projId: row.projId }).then((res) => {
    disabledInspect.value = !res
  })
}

// 流转标题
const statetUrnoverTitle = (v) => {
  const map = new Map([
    ['0', '进行中'],
    ['1', '已结束']
  ])
  return `是否将审查状态流转至“${map.get(v)}”`
}
// 流转操作
const statetUrnover = ({ planId, inspectStatus }) => {
  inspectPlanTurnover(planId, inspectStatus).then(() => {
    proTableRef.value.getTableData()
  })
}
// 删除
const onDelete = ({ planId }) => {
  del([planId]).then(() => {
    proTableRef.value.getTableData()
  })
}
// 评分结果
const onScoreResult = ({ planId }) => {
  inspectPlanResultScoreExport({ planId }).then((res) => {
    const blob = new Blob([res], { type: 'application/pdf' })
    const url = window.URL.createObjectURL(blob)
    window.open(url)
  })
}
// 表格多选
const selectionIds = ref([])
const selectionChange = (e) => {
  selectionIds.value = e.map((item) => item.planId)
}
// 导出
const downloadLoading = ref(false)
const onDownload = () => {
  if (!selectionIds.value.length) { return Message.warning('请先选择要导出的数据!') }
  downloadLoading.value = true
  getDownloadName(selectionIds.value).then((res) => {
    downloadPost(selectionIds.value, res).finally(() => {
      downloadLoading.value = false
    })
  })
}

// 获取 工程号/主合同号/项目编号 下拉框枚举
const remoteMethod = (query) => {
  return queryInspectProject({ searchStr: query }).then((res) => {
    options.project = res
  })
}
onMounted(() => {
  getMainUndertaking()
  getObserver()
  remoteMethod()
})
</script>

<template>
  <div>
    <ProTable
      ref="proTableRef"
      :get-table="getTable"
      :search-column="searchColumn"
      :table-column="tableColumn"
      :download-loading="downloadLoading"
      :show-left-option="['add', 'export']"
      :permission="permission"
      @selectionChange="selectionChange"
      @leftOptionChange="leftOptionChange"
    >
      <template #table_column_status="{ row }">
        <div class="flex-box">
          <span>{{
            getEnumlabel("inspect_plan_status", row.inspectStatus)
          }}</span>
          <WarningTextBtn
            v-if="['0', '1'].includes(row.inspectStatus)"
            v-permission="permission.turnover"
            :cbt="['是', '否']"
            :title="statetUrnoverTitle(row.inspectStatus)"
            @confirm="statetUrnover(row)"
          >流转</WarningTextBtn>
        </div>
      </template>
      <template #table_operate="{ row }">
        <div class="operate-box">
          <el-button
            v-permission="permission.edit"
            type="text"
            @click="onEdit(row)"
          >编辑</el-button>
          <WarningTextBtn
            v-permission="permission.del"
            :cbt="['是', '否']"
            title="确定删除本条数据吗？"
            @confirm="onDelete(row)"
          >删除</WarningTextBtn>
          <el-button
            v-permission="permission.scoreResult"
            type="text"
            :disabled="['0'].includes(row.inspectStatus)"
            @click="onScoreResult(row)"
          >评分结果</el-button>
        </div>
      </template>
    </ProTable>
    <Details
      ref="DetailsRef"
      title="审查策划"
      unique-id-name="planId"
      :form-column="formColumn"
      :form-rules="formRules"
      :add="add"
      :edit="edit"
      :default-form="defaultForm"
      @beforeClose="detailsClose"
    >
      <template #inspect1CompanyId_optionSlot="{ row }">
        <el-option
          v-for="item in optionFunc(row)"
          :key="item.id"
          :label="item.label"
          :value="item.id"
          :disabled="
            currentSelectProjct?.deptId === item.id ||
            DetailsRef.submitForm.inspect2CompanyId === item.id
          "
        />
      </template>
      <template #inspect2CompanyId_optionSlot="{ row }">
        <el-option
          v-for="item in optionFunc(row)"
          :key="item.id"
          :label="item.label"
          :value="item.id"
          :disabled="
            currentSelectProjct?.deptId === item.id ||
            DetailsRef.submitForm.inspect1CompanyId === item.id
          "
        />
      </template>
    </Details>
  </div>
</template>

<style scoped lang="scss">
.flex-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.operate-box {
  display: flex;
  align-items: center;
}
</style>
